package com.ruoyi.common.utils;
import org.lionsoul.ip2region.xdb.Searcher;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;

/*
@description:
@ClassName ParamMapUtils
@author chen
@create 2025-03-04 17:40
@Version 1.0
*/

public class ParamMapUtils extends HashMap<String,Object>
{
    private static Searcher searcher;

    public ParamMapUtils()
    {
        super();  // 显式调用父类构造函数
    }

    @SuppressWarnings("NullPointerException")
    @Override
    public ParamMapUtils put(String key, Object value)
    {
        super.put(key, value);
        return this;
    }

    public static void main(String[] args) throws IOException
    {
//        String appid = "wx0aa0f95bf2bb012b";
//        String secret = "08a63bdaa4ac5cb32f3c5577546549bb";
//        String code = "0b3Pi10w3wJRy43fle2w3e7Lq64Pi10h";
//        String requestUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code";
//        requestUrl = String.format(requestUrl, appid, secret, code);
//        // 3.构造请求,换取企业信息
//        String returnJson = HttpClientUtils.doGet(requestUrl, new HashMap<>());
//        System.out.println(returnJson);
        String ipAddress = getIpAddress("219.145.47.29");
        System.out.println(ipAddress);
    }


    public static String getIpAddress(String ip){
        if ("127.0.0.1".equals(ip) || ip.startsWith("192.168"))
        {
            return "局域网 ip";
        }
        if (searcher == null)
        {
            try {
                File file = ResourceUtils.getFile("classpath:ipdb/ip2region.xdb");
                String dbPath = file.getPath();
                searcher = Searcher.newWithFileOnly(dbPath);
            } catch (FileNotFoundException e)
            {
                e.printStackTrace();
            } catch (IOException e)
            {
                e.printStackTrace();
            }
        }
        String region = null;
        String errorMessage = null;
        try {
            region = searcher.search(ip);
        } catch (Exception e)
        {
            errorMessage = e.getMessage();
            if (errorMessage != null && errorMessage.length() > 256)
            {
                errorMessage = errorMessage.substring(0,256);
            }
            e.printStackTrace();
        }
        // 输出 region
        if(StringUtils.isNotEmpty(region))
        {
            String[] split = region.split("\\|");
            region = split[0] + split[2] + split[3];
        }
        return region;
    }

}
